package org.qs.webservice.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import org.qs.webservice.content.IReadContent;
import org.qs.webservice.dao.user.UsUserMapper;
import org.qs.webservice.domain.UsUser;
import org.qs.webservice.exception.QSReadException;
import org.qs.webservice.service.IreadFileService;
import org.qs.webservice.util.IReadUtils;
import org.qs.webservice.util.IdWorker;
import org.qs.webservice.util.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 文件操作接口
 * @ClassName: FileService 
 * @author xusaike 
 * @date 2015年11月18日 下午4:30:22 
 *
 */
@Service
public class IreadFileServiceImpl implements IreadFileService{
	@Resource
	UsUserMapper usUserMapper;
	
	public boolean saveFile(byte[] bytes,String name) {
		ByteArrayInputStream inputStream = null;
		FileOutputStream outputStream = null; 
		boolean ret = false;
		try {
			inputStream = new ByteArrayInputStream(bytes);
	        File file = new File(IReadContent.portrait_path, name);
	        if (!file.exists()) {
	        	file.createNewFile();
	        }
	        outputStream = new FileOutputStream(file);
	        byte[] buffer = new byte[1024];
	        int count = 0;
	        @SuppressWarnings("unused")
			long totalCount = 0L;
	        while ((count = inputStream.read(buffer)) > 0) {
	        	totalCount += count;
	        	outputStream.write(buffer, 0, count);
	        	outputStream.flush();
	        }
	        ret=true;

		}catch (Exception e) {
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("name", name);
			QSReadException.printf(e, "保存文件失败！",errorJson);
			System.out.println("保存文件失败!");
			ret=false;
		} finally {
			closeInputStream(inputStream);
	        closeOutputStream(outputStream);
		}
		return ret;
	}
	private void closeInputStream(InputStream inputStream){
		if (inputStream != null)
			try {
				inputStream.close();
			} catch (IOException e) {
				System.out.println("关闭文件流");
			}
	}
	private void closeOutputStream(OutputStream outputStream){
		if (outputStream != null)
			try {
				outputStream.close();
			} catch (IOException e) {
				System.out.println("关闭文件流");
			}
	}
	@Override
	public String saveFaceImage(byte[] bytes, String token) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		try {
			String userId = IReadUtils.getUserIdByTokenWithoutEffective(token);
			if(!StringUtils.isNullOrEmpty(userId)){
				UsUser user = usUserMapper.getCustomUserByUserid(Long.valueOf(userId));
				IdWorker idworker = new  IdWorker(1);
				if(user.getImage_url()!=null){
					try {
						Runtime.getRuntime().exec(new String[]{"/bin/sh","-c", 
						        "rm "+IReadContent.portrait_path+"/"+user.getImage_url()});
					} catch (IOException e) {
						Map<String,Object> errorJson = new HashMap<String,Object>();
						errorJson.put("token", token);
						QSReadException.printf(e, "io流异常！",errorJson);
					}  
				}
					 
				
				Long id=idworker.nextId();
				
				user.setImage_url("userfiles/portrait/"+id+"");
				
				try {
					if(this.saveFile(bytes,user.getImage_url())){
						int ret = usUserMapper.updateUserImage(user);
						if(ret==1){
							tokenMap.put("code", 200);
							tokenMap.put("content","修改头像成功");	
						}else{
							tokenMap.put("code", 403);
							tokenMap.put("reason","修改头像失败");
						}
						
					}else{
						tokenMap.put("code", 403);
						tokenMap.put("reason","修改头像失败");
					}
				} catch (Exception e) {
					Map<String,Object> errorJson = new HashMap<String,Object>();
					errorJson.put("token", token);
					QSReadException.printf(e, "修改头像失败！",errorJson);
					tokenMap = new HashMap<String,Object>();
					tokenMap.put("code", 403);
					tokenMap.put("reason","修改头像失败");
					
				}
				
			}else{
				tokenMap.put("code", 403);
				tokenMap.put("reason","用户未登录");
			}
			
		} catch (NumberFormatException e) {
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("token", token);
			QSReadException.printf(e, "类型转换失败！",errorJson);
			tokenMap = new HashMap<String,Object>();
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			
		}	
		return IReadUtils.beanToJson(tokenMap);
	}

}
